<?php
/**
 * Email: 1057780049@qq.com.
 * User: lanjiafeng
 * Date Time: 2021/5/31 15:49
 */

namespace addons\cms\controller\wxapp;

use app\admin\model\RecoveryCategory;
use app\admin\model\RecoveryDevoteset;
use app\admin\model\RecoveryOrder;
use app\admin\model\timetable\Usersetting;
use app\admin\model\UserAddress;
use think\Cache;
use think\Config;
use function count;
use function date;
use function explode;
use function implode;
use function in_array;
use function serialize;
use function sprintf;
use function strtotime;
use function time;
use function unserialize;
use const true;

class Recovery extends Base
{
	protected $noNeedLogin = ['category', 'select', 'devoteset', 'order'];

	public function category()
	{
		$categoryList = RecoveryCategory::where('price', '>', 0)
			->order('id desc')
			->cache(true, 10)
			->select();
		$this->success('', $categoryList);
	}

	/*分类选择器接口数据*/
	public function select()
	{
		$list = collection(RecoveryCategory::with('children')->field(['*'])->where('pid', 0)->order('id asc')->select())->toArray();
//        print_r($list);die;
		$data = [];
		foreach ($list as &$item) {
			$value = ['v' => $item['id'], 'n' => $item['name']];
			if ($item['children']) {
				foreach ($item['children'] as $key => &$child) {
					$value['c'][$key] = ['v' => $child['id'], 'n' => $child['name'], 'u' => $child['unit']];
				}
			} else {
				if ($item['unit'] && $item['price']) $value['c'][] = ['v' => $item['id'], 'n' => $item['name'], 'u' => $item['unit']];
			}
			if (isset($value['c'])) $data[] = $value;
		}
		$this->success('回收物品分类', $data);
	}

	/*客户端下单*/
	public function order()
	{
		/*查询订单上限设置*/
		$config = Config::get('site');
		$client_hour_order_limit = (int)$config['client_hour_order_limit'];//每小时可预约上限
		//一个小时内
		if ($client_hour_order_limit > 0) {
			$time = time() - 3600;
			$count = RecoveryOrder::where('createtime', '>', $time)->count();
			if ($count >= $client_hour_order_limit) $this->error("每小时可预约已达上限");
		}
		//每天
		$client_daily_order_limit = (int)$config['client_daily_order_limit'];//每日订单上限
		if ($client_daily_order_limit > 0) {
			$time = strtotime(date('Y-m-d', time()));//今日开始时间
			$count = RecoveryOrder::where('createtime', '>', $time)->count();
			if ($count >= $client_daily_order_limit) $this->error("每日订单已达上限");
		}


		$data = stripslashes(html_entity_decode($this->request->post('data')));
		$data = json_decode($data, true);
		//if ($data['typedata'] == '') $this->error("请选择客户类型");
		if ($data['ordertime'] == '请选择') {
			$this->error("请选择上门时间");
		} else {
			$data['ordertime'] = strtotime($data['ordertime']);
            /*if($data['ordertime'] == 1 || $data['ordertime'] == 1){
                $data['ordertime'] = time()+3600;
            }*/
			if ($data['ordertime'] < time()) $this->error("上门时间不能小于当前时间");
		}
		if ($data['category_id'] == '') $this->error("请选择类型");
		/*if ($data['name'] == '') $this->error("请填写联系人姓名");
		if ($data['mobile'] == '') $this->error("请填写联系人电话");*/
		if ($data['user_address_id'] == '') $this->error("请选择取货地址");
		$img = [];
		foreach ($data['images'] as $k => $val) {
			if (isset($val['url'])) $img[] = $val['url'];
		}
		$data['images'] = implode(',', $img);

		if (count($data['goodsinfo']) == 0) {
			$this->error("请添加物品信息");
		} else {
			foreach ($data['goodsinfo'] as &$v) {
				if ($v['recovery_category_id'] == 0) $this->error("请选择物品分类");
				//if ($v['weight'] <= 0) $this->error("物品重量不能小于0");
				if ($recoveryCategory = RecoveryCategory::get($v['recovery_category_id'])) {
					$v['price'] = sprintf('%.2f', $recoveryCategory->price);
				} else {
					$this->error("物品分类不存在");
				}
			}
		}
		$data['goodsinfo'] = serialize($data['goodsinfo']);
		$data['order_user_id'] = $this->auth->id;//下单用户id
		$data['status'] = 0;//0=待接单状态
        $data['category_two_value'] = trim($data['category_two_value'],',');
		/*订单地址信息更新*/
		$address = UserAddress::get($data['user_address_id']);
		if (!$address || ($address['user_id'] != $this->auth->id)) {
			$this->error(__('地址不存在'));
		}
		$data['lng'] = $address->lng;
		$data['lat'] = $address->lat;
		$model = new RecoveryOrder();
		$result = $model->allowField(true)->save($data);
		if ($result !== false) {
			$alisms = new \addons\alisms\library\Alisms();
			/*新订单通知管理员*/
			$mobiles = explode(';', $config['administrator_mobile']);
			foreach ($mobiles as $mobile) {
				if (strlen($mobile) === 11) {
					$alisms->mobile($mobile)
						->template('SMS_219753931')
						->sign('蓝色星球环保')
						->param([])
						->send();
				}
			}

			/*新订单通知在线骑手*/
			$list = Usersetting::hasWhere('user', ['signstatus' => '1'])
				->order('id DESC')
				->select();
			$markers = [];
			foreach ($list as &$row) {
				$user = \app\common\model\User::get($row->user_id);
				if ($user) {
					if (!$row->user->lat || !$row->user->lng) continue;
					if ($row->user->lastactivitytime < time() - 30 * 60) continue;
				} else {
					continue;
				}
				/*判断是否已经申请为骑手*/
				$riderApply = \app\admin\model\RiderApply::where('status', 1)->where('user_id', $row->user->id)->count();
				if (!$riderApply) {
					continue;
				}
				$alisms->mobile($user->mobile)
					->template('SMS_219743868')
					->sign('蓝色星球环保')
					->param([])
					->send();
			}
			$tips = 'newOrder:tips:number';
			Cache::inc($tips);
			$this->success('下单成功');
		} else {
			$this->error(__('下单失败，请重试'));
		}
	}

	/*订单详情*/
	public function orderDetail()
	{
		$id = (int)$this->request->post('id');//订单id
		if (!$id) $this->error(__('Operation failed'));
		$order = RecoveryOrder::with(['rider'])->find(['id' => $id])->toArray();
		if (!$order || ($order['order_user_id'] != $this->auth->id)) {
			$this->error(__('订单不存在'));
		}
		$order['ordertime_text'] = date("Y-m-d H:i", $order['ordertime']);
		$order['createtime_text'] = date("Y-m-d H:i:s", $order['createtime']);
		/*计算预计回收价格*/
		$goodsinfos = unserialize($order['goodsinfo']);
		$estimate_price = 0;
        $estimate_price_end = 0;
		$goodsList = [];
		foreach ($goodsinfos as $goodsinfo) {
			$data = RecoveryCategory::get($goodsinfo['recovery_category_id']);
			if ($data) {
				$data = $data->toArray();
			} else {
				$data['price'] = isset($goodsinfo['price']) ?? 0;
			}
            if (strpos($goodsinfo['weight'], '-') !== false){
                $wei = explode('-',$goodsinfo['weight']);
                $estimate_price += $data['price'] * $wei[0];
                // $estimate_price += $price * $goodsinfo['weight'];
                $estimate_price_end += $data['price'] * $wei[1];

                $estimate_price1 = $data['price'] * $wei[0];
                // $estimate_price += $price * $goodsinfo['weight'];
                $estimate_price_end1 = $data['price'] * $wei[1];
                $estimate_weight1 = $wei[0];
                $estimate_weight_end1 = $wei[1];
            }else{
                $estimate_price += $data['price'] * $goodsinfo['weight'];
                $estimate_price_end += $data['price'] * $goodsinfo['weight'];

                $estimate_price1 = $data['price'] * $goodsinfo['weight'];
                $estimate_price_end1 = $data['price'] * $goodsinfo['weight'];
                $estimate_weight1 = $goodsinfo['weight'];
                $estimate_weight_end1 = $goodsinfo['weight'];
            }
            if(sprintf("%.2f", $estimate_price1) == sprintf("%.2f", $estimate_price_end1)){
                $estimate_price_dev1 = sprintf("%.2f", $estimate_price1);
            }else{
                $estimate_price_dev1 = sprintf("%.2f", $estimate_price1).'-'.sprintf("%.2f", $estimate_price_end1);
            }
            if(sprintf("%.2f", $estimate_weight1) == sprintf("%.2f", $estimate_weight_end1)){
                $estimate_weight_dev1 = sprintf("%.2f", $estimate_weight1);
            }else{
                $estimate_weight_dev1 = sprintf("%.2f", $estimate_weight1).$goodsinfo['unit'].'-'.sprintf("%.2f", $estimate_weight_end1);
            }
			$goodsList[] = [
				'name' => $goodsinfo['recovery_category_name'],
				'price' => $data['price'] . '元/' . $goodsinfo['unit'],
				'weight' => $estimate_weight_dev1 . $goodsinfo['unit'],
				//'weight' => $goodsinfo['weight'] . $goodsinfo['unit'],
				'total_price' => $estimate_price_dev1
				//'total_price' => sprintf("%.2f", $goodsinfo['weight'] * $data['price'])
			];
			//$estimate_price += $data['price'] * $goodsinfo['weight'];
		}
        if(sprintf("%.2f", $estimate_price) == sprintf("%.2f", $estimate_price_end)){
            $estimate_price_dev = sprintf("%.2f", $estimate_price);
        }else{
            $estimate_price_dev = sprintf("%.2f", $estimate_price).'-'.sprintf("%.2f", $estimate_price_end);
        }
		$order['estimate_price'] = $estimate_price_dev;
		$order['goodsList'] = $goodsList;

		if ($order['real_goods_info']) {
			/*计算实际回收价格*/
			$realgoodsinfos = unserialize($order['real_goods_info']);
			$realestimate_price = 0;
			$realgoodsList = [];
			$order['estimate_price'] = 0;
			$order['goodsList'] = [];
			foreach ($realgoodsinfos as $realgoodsinfo) {
				if ($data = RecoveryCategory::where(['fa_recovery_category.id' => $realgoodsinfo['recovery_category_id']])->find()) {
					$data = $data->toArray();
					if ($parent = RecoveryCategory::where(['fa_recovery_category.id' => $data['pid']])->find()) $data['name'] = $parent['name'] . ',' . $data['name'];
				}
				$realgoodsList[] = [
					'name' => $realgoodsinfo['recovery_category_name'],
					//'name' => $realgoodsinfo['name'],
					'price' => $realgoodsinfo['price'] . '元/' . $realgoodsinfo['unit'],
					'weight' => $realgoodsinfo['weight'] . $data['unit'],
					'total_price' => sprintf("%.2f", $realgoodsinfo['weight'] * $realgoodsinfo['price'])
				];
				$realestimate_price += $realgoodsinfo['price'] * $realgoodsinfo['weight'];
			}
			$order['estimate_price'] = sprintf("%.2f", $realestimate_price);
			$order['goodsList'] = $realgoodsList;
		}

		$this->success('', $order);
	}

	/*订单评分*/
	public function orderEvaluate()
	{
		$id = (int)$this->request->post('id');//订单id
		if (!$id) $this->error(__('Operation failed'));
		$order = RecoveryOrder::get($id);
		if (!$order || ($order['order_user_id'] != $this->auth->id)) {
			$this->error(__('订单不存在'));
		}
		if (($order['status'] != 3)) {
			$this->error(__('订单未完成'));
		}
		if (($order['status'] == 4)) {
			$this->error(__('订单已评价'));
		}
		$punctually = $this->request->post('punctually/d', 0);//准时率
		$serviceAttitude = $this->request->post('serviceAttitude/d', 0);//服务态度
		$evaluateContent = $this->request->post('evaluateContent/s', '');//评价内容
//        if ($evaluateContent == '' ) $this->error(__('评价内容不能为空'));
		$order->punctually = $punctually;
		$order->serviceAttitude = $serviceAttitude;
		$order->evaluateContent = $evaluateContent;
		$order->evaluatetime = time();//评分时间
		$order->status = 4;//修改订单为已评价状态
		$order->save();
		$this->success(__('Operation completed'));
	}

	/*绿色贡献值计算*/
	public function devoteset()
	{
		$list = RecoveryDevoteset::where(1)
			->with(['recoverycategory'])
			->order('id asc')
			->cache(false)
			->select();
		$orderList = RecoveryOrder::whereOr('status', '3')->whereOr('status', '4')->where('order_user_id', $this->auth->id)->column('real_goods_info');
		$categoryList = [];
		foreach ($orderList as &$v) {
			$v = unserialize($v);
			$categoryList += $v;
		}

		foreach ($list as &$row) {
			/*查询该分类下的所有子集  id集合*/
			$childIds = RecoveryCategory::where('pid', $row['recovery_category_id'])->column('id');

			$total_weight = 0;
			foreach ($categoryList as $val) {
				if (in_array($val['recovery_category_id'], $childIds)) {
					$total_weight += $val['weight'];
				}
			}
			$devoteparam = unserialize($row->devoteparam);
			foreach ($devoteparam as &$item) {
				$item['total'] = sprintf('%.2f', (float)$total_weight * (float)$item['proportion']);
			}
			$row->devoteparam = $devoteparam;
		}
		$this->success('', $list);
	}
}
